package top.marken.onlineclass.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.marken.onlineclass.model.entity.User;
import top.marken.onlineclass.model.request.LoginRequest;
import top.marken.onlineclass.service.UserService;
import top.marken.onlineclass.util.JsonData;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 用户相关业务接口
 */
@RestController
@RequestMapping("/api/v1/pri/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注册
     * @param userInfo 用户信息
     * @return 返回JSON提示
     */
    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String, String> userInfo) {
        int code = userService.addOne(userInfo);
        String msg;
        switch (code) {
            case JsonData.CODE_ERROR:
                msg = "注册用户时发生错误！";
                break;
            case JsonData.CODE_SUCCESS:
                msg = "注册成功！";
                break;
            case JsonData.CODE_FAIL:
                msg = "用户信息不规范，注册失败！";
                break;
            default:
                msg = "未知错误！";
        }
        return new JsonData(code,null,msg);
    }

    /**
     * 用户登录
     * @param loginRequest 登录信息
     * @return JSON提示信息
     */
    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest) {
        String token = userService.login(loginRequest);
        return token == null ? JsonData.buildFail(null) : JsonData.buildSuccess(token);
    }

    /**
     * 查询用户信息
     * @param request 根据get请求中的user_id参数查询用户信息
     * @return 用户信息JSON数据
     */
    @GetMapping("/info")
    public JsonData info(HttpServletRequest request) {
        Integer id = (Integer) request.getAttribute("user_id");
        if (id == null) {
            return JsonData.buildFail(null,"用户信息查询失败！");
        }
        User user = userService.findById(id);
        return JsonData.buildSuccess(user);
    }
}
